package com.example.springboot.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

public class LoginFailureHandler implements AuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authentication) throws IOException, ServletException {

		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");

		if (authentication instanceof UsernameNotFoundException) {
			response.getWriter().println("用户名不存在");

		} else if (authentication instanceof BadCredentialsException) {
			response.getWriter().println("密码错误");

		} else {
			response.getWriter().println(authentication.getLocalizedMessage());

		}

		response.getWriter().flush();

	}
}
